<script setup>
	import { ref, getCurrentInstance } from "vue"
	import loading from "./loading.vue"
	import { chatbotMessageStore } from "@/stores/chatbotMessage.js"
	const chatbotMessage = chatbotMessageStore()

	const instance = getCurrentInstance()
	const appContext = ref(null)
	appContext.value = instance.appContext.config.globalProperties

	// 复制链接
	const copyText = (url) => {
		uni.setClipboardData({
			data: url,
			success() {
				uni.showToast({ icon: 'none', title: '链接已复制,请到浏览器打开' })
			}
		})
	}
</script>

<template>
	<template v-for="(item,index) in chatbotMessage.messages" :key="index">
		<!-- 用户发送 -->
		<view class="user-box" v-if="item.role==='user'">
			<text class="user-message" selectable>{{item.content}}</text>
		</view>
		<!-- ai回复 -->
		<view class="ai-message" v-if="item.role==='assistant'">
			<towxml :nodes="appContext.$towxml(item.content,'markdown')"></towxml>
			<loading v-if="item.finish_reason === 'start'"></loading>
			<!-- 联网查询的数据 -->
			<view v-if="item.web_search.length > 0">
				<text class="recommend-tips">我还为你推荐以下内容</text>
				<view class="recommend-content">
					<text class="recommend-item" v-for="(itema,indexa) in item.web_search" :key="indexa"
						@click="copyText(itema.link)">{{indexa + 1}}.{{itema.title}} —— {{itema.media}}</text>
				</view>
			</view>
		</view>
	</template>
</template>

<style lang="scss" scoped>
	.user-box {
		display: flex;
		width: 100%;
		justify-content: flex-end;

		.user-message {
			background-color: #20c57D;
			border-radius: 20rpx 20rpx 4rpx 20rpx;
			color: #fff;
			padding: 15rpx;
			margin: 30rpx 20rpx 0 20rpx;
			display: inline-block;
		}
	}


	.ai-message {
		background-color: #fff;
		border-radius: 20rpx 20rpx 20rpx 4rpx;
		color: #333;
		padding: 15rpx;
		margin: 30rpx 20rpx 0 20rpx;

		.recommend-tips {
			background-color: $bg-color;
			border-radius: 10rpx;
			margin: 20rpx 0;
			padding: 15rpx;
			font-weight: bold;
		}

		.recommend-content {
			background-color: $bg-color;
			border-radius: 10rpx;
			padding: 15rpx;

			.recommend-item {
				margin-bottom: 15rpx;
				color: #006c45;
				@include ellipsis();

				&:last-child {
					margin-bottom: 0;
				}
			}
		}
	}
</style>